<script lang="ts" setup>
import { reactive, ref, computed } from "vue"
import { ElTable, FormInstance } from "element-plus"
import { Search, Refresh, Download } from "@element-plus/icons-vue"
// 接口
import { getBroadBand, downloadDataRequest } from "@/api/SZ/broadBand"
import { getqueryTeamName } from "@/api/SZ/SZXxfy"
import { shortcuts, Y, M, D } from "@/utils/dateSet"
const loading = ref(false)
defineOptions({
  name: "SZBroadBand"
})
const shopList = ref<any>([])
const formRef = ref<FormInstance | null>(null)
/**店铺数据 */
const getShopList = () => {
  getqueryTeamName().then((res: any) => {
    if (res.code == 200) {
      shopList.value = res.data
      // console.log(res)
    }
  })
}
getShopList()

// #region 查
// 状态管理
const columns = ref<ColumnConfig[]>([])
const responseData = ref<any[]>([])
const getList = () => {
  getBroadBand({
    dianPu: searchData.dianPu,
    state: searchData.state,
    startTime: searchData.startTime,
    endTime: searchData.endTime
  })
    .then((res: any) => {
      responseData.value = res.data || [] // 存储原始数据
      processResponseData(res.data) // 处理原始数据
    })
    .catch(() => (responseData.value = []))
    .finally(() => (loading.value = false))
}
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  time: [
    new Date(Y.value, M.value, D.value, 0, 0, 0).getTime(),
    new Date(Y.value, M.value, D.value, 23, 59, 59).getTime()
  ],
  startTime: new Date().getTime(),
  endTime: new Date().getTime(),
  dianPu: "",
  state: []
})
const downloadData = async () => {
  downloadDataRequest({
    startTime: searchData.startTime,
    endTime: searchData.endTime,
    dianPu: searchData.dianPu,
    state: searchData.state
  })
    .then((res: any) => {
      const blob = new Blob([res.data], {
        type: "application/xlsx;charset=utf-8"
      })
      const downloadElement = document.createElement("a")
      const href = window.URL.createObjectURL(blob)
      downloadElement.href = href
      downloadElement.download = "宽带销量.xlsx"
      document.body.appendChild(downloadElement)
      downloadElement.click()
      window.URL.revokeObjectURL(href)
      console.log("下载成功")
    })
    .catch(() => console.log("下载失败"))
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  formRef.value?.clearValidate()
  fetchData()
  console.log("重置")
}
const handleSearch = () => {
  fetchData()
  console.log("查询")
}
const timeChange = (dates: [Date, Date] | null) => {
  if (!dates) return
  searchData.startTime = new Date(dates[0]).getTime()
  searchData.endTime = new Date(dates[1]).getTime()
}
// #endregion

interface ColumnConfig {
  prop: string
  label: string
}

// 数据处理逻辑
const processResponseData = (data: any[]) => {
  // 空数据保护
  if (!data || !Array.isArray(data) || data.length === 0) {
    columns.value = []
    responseData.value = []
    return
  }

  // 强制初始化列数据
  columns.value = []

  // 提取表头
  const headerObj = data.find((item) => item.head)
  if (headerObj?.head) {
    columns.value = headerObj.head.map((header: any) => ({
      prop: header,
      label: header
    }))
  }

  // 提取数据行（过滤表头对象）
  responseData.value = data.filter((item) => !item.head)

  // 合计行标记（根据业务规则）
  responseData.value.forEach((row) => {
    row.isTotal = isTotalRow(row)
  })
}

// 判断是否合计行（根据数据特征）
const isTotalRow = (row: any) => {
  return row["套餐id"] === "合计：" // 或根据实际标识调整
}

// 数值格式化（解决混合类型问题）
const formatNumber = (value: any) => {
  // 空值处理
  if (value === null || value === undefined) return "--"

  // 排除非数值内容
  const num = Number(value)
  return isNaN(num) ? value : num.toLocaleString()
}

// 接口请求
const fetchData = async () => {
  getList()
  processResponseData(responseData.value)
}

const dynamicColumns = computed(() =>
  columns.value
    .filter((col: any) => !col.isFixed)
    .map((col: any) => ({
      ...col,
      uid: `${col.prop}_dynamic_${Date.now()}`, // 动态列唯一标识
      shouldHighlight: (val: any) => Number(val) > 0, // 高亮逻辑复用
      formatter: col.isNumeric ? formatNumber : "--" // 统一数字格式化, 仅对数值列应用格式化
    }))
)

// 高亮判断（防御性处理）
const shouldHighlight = (val: any) => {
  const num = Number.parseFloat(val)
  return !Number.isNaN(num) && num > 0
}

const handleClear = () => {
  searchData.dianPu = ""
}

// onMounted(fetchData)
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="time" label="时间">
          <el-date-picker
            v-model="searchData.time"
            type="datetimerange"
            range-separator="到"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="shortcuts"
            @change="timeChange"
          />
        </el-form-item>

        <el-form-item prop="dianPu" label="店铺">
          <el-select v-model="searchData.dianPu" clearable filterable placeholder="请选择" @clear="handleClear">
            <el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>

        <br />

        <el-form-item prop="state" label="状态">
          <el-checkbox-group v-model="searchData.state">
            <el-checkbox label="已完成" value="已完成" />
            <el-checkbox label="安装中" value="安装中" />
            <el-checkbox label="处理中" value="处理中" />
            <el-checkbox label="未提交" value="未提交" />
            <el-checkbox label="安装失败" value="安装失败" />
          </el-checkbox-group>
        </el-form-item>

        <br />

        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          <el-button :icon="Download" @click="downloadData">下载</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 中间部分 -->
    <el-card v-loading="loading" shadow="never">
      <!-- 中间渲染内容 -->
      <div class="table-center dynamic-table-container">
        <el-table
          :data="responseData"
          :row-key="(row) => row.id"
          v-loading="loading"
          style="width: 120%"
          :max-height="530"
        >
          <template v-for="(col, index) in dynamicColumns" :key="col.uid">
            <el-table-column
              :prop="col.prop"
              :label="col.label"
              :fixed="index < 2 ? 'left' : undefined"
              :style="index === 1 ? { left: 20 } : undefined"
            >
              <template #default="{ row }">
                <span
                  :class="{
                    'highlight-cell': col.shouldHighlight(row[col.prop]),
                    'total-style': row.isTotal
                  }"
                >
                  {{ row[col.prop] }}
                </span>
              </template>
            </el-table-column>
          </template>

          <!-- 空状态处理 -->
          <template #empty>
            <el-empty :image-size="100" description="暂无数据" />
          </template>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
// .box-card {
//   height: 70px;
//   margin-bottom: 20px;
// }
.search-wrapper {
  margin-bottom: 20px;
}

.middle-top {
  margin-bottom: 20px;
}

.table-center {
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: flex-end;
}
</style>
